window.addEventListener("load", function() {
	var newmsg = document.getElementById("button-newmsg");

	newmsg.type = "menu";
	newmsg.removeAttribute("oncommand");
		
	if(!newmsg.childNodes.length) {
		newmsg.appendChild(document.createElement("menupopup"));
	}
	else {
		newmsg.childNodes[0].insertBefore(document.createElement("menuseparator"), newmsg.childNodes[0].childNodes[0]);
	}
	
	// every time the popup menu hides we want to clear the identities
	// that we added so that any changes through the preferences dialog
	// are reloaded.
	newmsg.childNodes[0].addEventListener("popuphidden", function() {
		for(var i = this.childNodes.length; i >= 0; --i) {
			var item = this.childNodes[i];
			
			if(item && item.name == "identity-item") {
				this.removeChild(item);
			}
		}
	}, false);	
	
	// every time the popup menu is shown we need to reload and repopulate
	// the list of identities
	newmsg.childNodes[0].addEventListener("popupshowing", function() {
		var ids = (new identities()).identities;
		
		for(var i = 0; i < ids.length; i++) {
			var item = document.createElement("menuitem");
			
			item.identity = ids[i];
			item.name = "identity-item";
			item.setAttribute("name", "identity-item");
			item.setAttribute("label", item.identity.name());
			item.setAttribute("src", "chrome://messenger/skin/icons/folder-sent.png");
			item.setAttribute("class", "menuitem-iconic");
			item.addEventListener("click", function() {
				this.identity.compose();
				return;
			}, false);
			
			this.insertBefore(item, this.childNodes[0]);
		}
	}, false);
	
	
}, false);
